const OpenAI = require("openai");
const { db, query } = require("../../db/db");
const util = require("util");
const moment = require("moment");
const { log } = require("util");

const openai = new OpenAI({
  baseURL: "https://api.deepseek.com",
  apiKey: "sk-fafc83f80321415c943e00c8c6410ed7",
});

async function WithAiDialogue(req, res) {
  let Usercontent = req.body.Usercontent;
  let UserId = Number(req.params.username);
  /*   console.log("3333", Usercontent); */
  if (Usercontent === "") {
    return res.send({
      status: 0,
      content: "请勿输入空白内容",
    });
  }

  let isRequestAborted = false;
  // 监听客户端中断请求
  res.on("close", () => {
    if (!res.writableFinished) {
      console.log("客户端中断了请求");
      isRequestAborted = true;
      res.end();
    }
  });

  db.getConnection((err, connection) => {
    if (err) {
      return res.status(500).send({ status: 0, message: "数据库连接失败" });
    }

    connection.beginTransaction(async (err) => {
      if (err) {
        connection.release();
        return res.status(500).send({ status: 0, message: "事务启动失败" });
      }

      // 存储用户输入
      const Insert_user =
        "Insert into Ai_Chat_Record (UserId,ChatContent,ChatTime,Role) values (?,?,?,?)";
      connection.query(
        Insert_user,
        [UserId, Usercontent, moment().format("YYYY-MM-DD HH:mm:ss"), "user"],
        (err, result) => {
          if (err) {
            console.log("err", err);
            return connection.rollback(() => {
              connection.release();
              res.status(500).send({ status: 0, message: "用户输入存储失败" });
            });
          }

          // 获取全部内容
          const Select_user = util.format(
            "SELECT UserId, IFNULL(ChatContent, '') AS ChatContent, IFNULL(ChatTime, '') AS ChatTime, IFNULL(Role, '') AS Role, IsSatisfied FROM Ai_Chat_Record WHERE UserId = %s \
            ORDER BY ChatTime DESC LIMIT %s",
            UserId,
            20
          );

          connection.query(Select_user, async (err, result) => {
            if (err) {
              return connection.rollback(() => {
                connection.release();
                res
                  .status(500)
                  .send({ status: 0, message: "查询聊天记录失败" });
              });
            }

            let AllChatList = result
              .map((item) => ({
                role: item.Role,
                content: item.ChatContent,
              }))
              .reverse();

            // 设置响应头，支持流式传输
            res.setHeader("Content-Type", "text/event-stream");
            res.setHeader("Transfer-Encoding", "chunked");

            // 调用流式 API
            const stream = await openai.chat.completions.create({
              messages: AllChatList,
              model: "deepseek-chat",
              stream: true, // 启用流式响应
            });
            let aiResponse = ""; // 用于存储完整的 AI 响应
            let IsStop = 0;
            /* console.log("stream", stream, AllChatList); */
            // 逐块发送数据给前端
            for await (const chunk of stream) {
              if (isRequestAborted) {
                // 如果客户端中断了请求，停止发送数据
                console.log("请求已中断，停止流式传输");
                IsStop = 1;
                break;
              }
              const content = chunk.choices[0]?.delta?.content || "";
              aiResponse += content; // 逐步收集 AI 的响应内容
              res.write(content); // 将数据块发送给前端
            }
            /*  res.send(stream); */
            // 结束响应
            res.end();

            // 将完整的 AI 响应存入数据库
            const Insert_ai =
              "INSERT INTO Ai_Chat_Record (UserId, ChatContent, ChatTime, Role,IsStop) VALUES (?,?,?,?,?)";

            connection.query(
              Insert_ai,
              [
                UserId,
                aiResponse,
                moment().format("YYYY-MM-DD HH:mm:ss"),
                "assistant",
                IsStop,
              ],
              (err, result) => {
                if (err) {
                  return connection.rollback(() => {
                    connection.release();
                    console.error("AI 响应存储失败:", err);
                  });
                }

                // 提交事务
                connection.commit((err) => {
                  if (err) {
                    return connection.rollback(() => {
                      connection.release();
                      console.error("事务提交失败:", err);
                    });
                  }
                  connection.release();
                  console.log("Transaction completed successfully.");
                });
              }
            );
          });
        }
      );
    });
  });
}

module.exports = {
  WithAiDialogue,
};
